import json
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.request import Request
from rest_framework.response import Response
from django.http import JsonResponse

from .serializers import BookSerializers
from .models import BookInfo
# Create your views here.


class BookView(GenericAPIView):
    queryset = BookInfo.objects.all()  # 指定查询集
    serializer_class = BookSerializers  # 指定序列化器

    def get(self, request, pk):
        # 序列化的时候要将模型类对象传递给instance参数，反序列化的时候要将被反序列化的数据传递给data参数
        # 查询书籍方法一:
        book = self.get_object()
        ser = self.get_serializer(book)  # 将模型类对象传递给instance，不需要考虑序列化器定义时的required=True的参数

        # # 查询书籍方法二:
        # book = BookInfo.objects.get(id=pk)
        # # 因为序列化器定义时候id和name字段是被要求的必须的，所以被反序列化的数据至少包含这两个参数
        # # 返回的结果也只包含data指明的字段
        # data = {'id': book.id, 'name': book.name, 'readcount': book.readcount, 'commentcounts': book.commentcount}
        # ser = BookSerializers(data=data)
        # ser.is_valid(raise_exception=True)  # raise_exception置为True时，当缺少参数是直接抛出异常
        # print(ser.errors)
        # print(ser.validated_data)
        # print(ser.data)

        # ser.data 是序列化

        return Response(ser.data)

    def put(self, request, pk):
        """
        更新图书
        :param request:
        :param pk:
        :return:
        """
        book = self.get_object()
        data = request.data

        ser = self.get_serializer(book, data)
        ser.is_valid()
        # print(ser.errors)  # 查看验证结果，成功返回空字典，失败返回错误信息
        ser.save()
        print(ser.validated_data)

        return Response(ser.data)


class BooksView(GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializers

    def get(self, request):
        book = self.get_queryset()
        ser = self.get_serializer(book, many=True)

        return Response(ser.data)

    def post(self, request):
        """
        增加图书
        :param request:
        :return:
        """
        data = request.data
        ser = self.get_serializer(data=data)
        ser.is_valid(raise_exception=True)
        book = ser.save()  # 序列化器中不传入instance时调用save方法调用的就是create，新增数据的方法

        return Response(ser.data)

